package com.kawins.util.bean;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rankai
 *         createTime 2017-11-2017/11/8 16:21
 */
public class EnumUtil {

    /**
     * 将枚举转化为List对象集合,例如枚举
     * SYS_ROOT(0, "系统管理员"),
     * ADMIN(1, "顶级机构管理员"),
     * ORG_ADMIN(2, "机构管理员"),
     * MANAGER(3, "客户经理");
     * private int code;
     * private String name;
     * 调用此方法转换为Json得到为
     * [{"code":0,"name":"系统管理员"},{"code":1,"name":"顶级机构管理员"},{"code":2,"name":"机构管理员"},{"code":3,"name":"客户经理"}]
     *
     * @param ref
     * @param <T>
     * @return
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static <T> List<Object> bulidListBean(Class<T> ref) {
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(ref);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            T[] enumConstants = ref.getEnumConstants();
            List<Object> list = new ArrayList<>(0);
            for (T enumConstant : enumConstants) {
                Map<String, Object> map = new HashMap<>();
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    String name = propertyDescriptor.getName();
                    if (!name.equals("class") && !name.equals("declaringClass")) {
                        Method getter = propertyDescriptor.getReadMethod();
                        Object invoke = getter.invoke(enumConstant);
                        map.put(name, invoke);
                    }
                }
                list.add(map);
            }
            return list;
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
